package cn.com.api.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import cn.com.api.service.ApiUploadService;
import cn.com.qiniu.UthinkUploader;
import cn.com.util.Base64Util;
import cn.com.util.ImageUtils;

@Service
public class ApiUploadServiceImpl implements ApiUploadService {

	public List<String> uploadFileToQiNiu(MultipartFile[] files)
			throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		List<String> urList = new ArrayList<String>();
		for (int i = 0; i < files.length; i++) {
			String date = sdf.format(new Date());// 年月
			String fileName = date + i + "_" + files[i].getOriginalFilename();
			// 上传到qiniu后，返回的绝对路径，要保存到数据库中。
			Integer sourceType = UthinkUploader.getSourceType(fileName);
			if (sourceType != null) {// 文件格式支持的可以上传
				String returnurl = UthinkUploader.send(fileName,
						files[i].getBytes(), sourceType);
				urList.add(returnurl);
			}
		}
		return urList;
	}

	public List<String> uploadFileToServer(MultipartFile[] files,
			HttpServletRequest request, String foldername) throws Exception {
		List<String> urList = new ArrayList<String>();
		for (int i = 0; i < files.length; i++) {
			String returnurl = ImageUtils.uploadFile(request, foldername,
					files[i]);
			urList.add(returnurl);
		}
		return urList;
	}

	public String uploadBase64Str(String imgBase64Str, String suffix)
			throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String date = sdf.format(new Date());// 年月
		String fileName = date + "." + suffix;
		byte[] bytes = Base64Util.decode(imgBase64Str);
		// 上传到qiniu后，返回的绝对路径，要保存到数据库中。
		Integer sourceType = UthinkUploader.getSourceType(fileName);
		String returnurl = UthinkUploader.send(fileName, bytes, sourceType);
		return returnurl;
	}
}
